<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Menu as IconMenu,
  User as IconUser,
  House as IconHouse,
  Box as IconBox,
  Goods as IconGoods,
  ArrowDown as IconArrowDown,
  ArrowUp as IconArrowUp,
  Search as IconSearch,
  Lock
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import userApi from '@/api/user'


const router = useRouter()
const isCollapse = ref(false)
const userRole = ref('')
const userName = ref('')
const roleMap = {
  admin: '管理员',
  manager: '经理',
  operator: '操作员'
}

onMounted(() => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    const user = JSON.parse(userInfo)
    userRole.value = roleMap[user.role as keyof typeof roleMap] || user.role
    userName.value = user.realName || user.username
  }
})

const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  ElMessage.success('退出登录成功')
  router.push('/login')
}

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 修改密码相关
const updatePasswordDialogVisible = ref(false)
const updatePasswordFormRef = ref<FormInstance>()
const updatePasswordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 删除用户相关
const deleteUserDialogVisible = ref(false)
const userToDelete = ref<{
  userId: number
  username: string
} | null>(null)

const handleDeleteUser = async () => {
  if (!userToDelete.value) return
  try {
    await userApi.deleteUser(userToDelete.value.userId)
    ElMessage.success('用户删除成功')
    deleteUserDialogVisible.value = false
    userToDelete.value = null
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '删除用户失败，请稍后重试')
  }
}

// 验证确认密码是否一致
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== updatePasswordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

const handleUpdatePassword = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // No need to get userInfo or userId here anymore, backend uses token
        const dataToSend = {
          oldPassword: updatePasswordForm.oldPassword,
          newPassword: updatePasswordForm.newPassword
        };

        // Call the updated updatePassword function which only takes the data object
        await userApi.updatePassword(dataToSend);

        ElMessage.success('密码修改成功');
        updatePasswordDialogVisible.value = false;
        updatePasswordForm.oldPassword = '';
        updatePasswordForm.newPassword = '';
        updatePasswordForm.confirmPassword = '';

        // 修改密码成功后，重新登录
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        router.push('/login');
      } catch (error: any) {
        console.error('Error updating password:', error); // Log the error
        ElMessage.error(error.response?.data?.message || '密码修改失败，请稍后重试');
      }
    }
  });
};

const handleDialogClose = () => {
  updatePasswordForm.oldPassword = ''
  updatePasswordForm.newPassword = ''
  updatePasswordForm.confirmPassword = ''
  if (updatePasswordFormRef.value) {
    updatePasswordFormRef.value.resetFields()
  }
}
</script>

<template>
  <el-container class="layout-container">
    <!-- 顶部导航栏 -->
    <el-header class="layout-header">
      <div class="header-left">
        <el-button type="text" @click="toggleSidebar">
          <el-icon :size="20" color="#fff">
            <icon-menu />
          </el-icon>
        </el-button>
        <h2 class="system-title">仓库管理系统</h2>
      </div>
      <div class="header-right">
        <span class="username">{{ userName }} ({{ userRole }})</span>
        <el-dropdown>
          <el-button type="text">
            <el-icon :size="20" color="#fff">
              <icon-user />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="updatePasswordDialogVisible = true">修改密码</el-dropdown-item>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <el-container>
      <!-- 侧边菜单栏 -->
      <el-aside :width="isCollapse ? '64px' : '200px'" class="layout-aside">
        <el-menu
          :collapse="isCollapse"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409eff"
          unique-opened
          router
        >
          <el-menu-item index="/">
            <el-icon><icon-house /></el-icon>
            <template #title>首页</template>
          </el-menu-item>

          <el-sub-menu index="1" v-if="userRole === '管理员' || userRole === '经理'">
            <template #title>
              <el-icon><icon-user /></el-icon>
              <span>用户管理</span>
            </template>
            <el-menu-item index="/user/list">用户列表</el-menu-item>
            <el-menu-item index="/user/info">更新用户信息</el-menu-item>
            <el-menu-item @click="updatePasswordDialogVisible = true">修改密码</el-menu-item>
            <!-- <el-menu-item v-if="userRole === '管理员'" @click="deleteUserDialogVisible = true">删除用户</el-menu-item> -->
          </el-sub-menu>

          <el-sub-menu index="2">
            <template #title>
              <el-icon><icon-box /></el-icon>
              <span>仓库管理</span>
            </template>
            <el-menu-item index="/warehouse/list">仓库列表</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="3">
            <template #title>
              <el-icon><icon-goods /></el-icon>
              <span>物品管理</span>
            </template>
            <el-menu-item index="/category/list">物品分类</el-menu-item>
            <el-menu-item index="/item/list">物品列表</el-menu-item>
            <el-menu-item index="/inbound/list">入库记录</el-menu-item>
            <el-menu-item index="/outbound/list">出库记录</el-menu-item>
            <el-menu-item index="/inventory/list">库存查询</el-menu-item>
            <el-menu-item index="/records/stats">出入库统计</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="layout-main">
        <router-view />
        
        <!-- 删除用户弹窗 -->
        <el-dialog
          v-model="deleteUserDialogVisible"
          title="删除用户"
          width="400px"
          :close-on-click-modal="false"
        >
          <div class="delete-user-content">
            <p>确定要删除该用户吗？此操作不可恢复。</p>
          </div>
          <template #footer>
            <el-button @click="deleteUserDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="handleDeleteUser">确认删除</el-button>
          </template>
        </el-dialog>

        <!-- 修改密码弹窗 -->
        <el-dialog
          v-model="updatePasswordDialogVisible"
          title="修改密码"
          width="400px"
          :close-on-click-modal="false"
          @close="handleDialogClose"
        >
          <el-form
            ref="updatePasswordFormRef"
            :model="updatePasswordForm"
            :rules="passwordRules"
            label-width="100px"
            style="width: 100%"
            status-icon
          >
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input
                v-model="updatePasswordForm.oldPassword"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入旧密码"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="updatePasswordForm.newPassword"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入新密码"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="updatePasswordForm.confirmPassword"
                :prefix-icon="Lock"
                type="password"
                placeholder="请再次输入新密码"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                style="width: 100%"
                @click="handleUpdatePassword(updatePasswordFormRef)"
              >
                确认修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
.layout-container {
  height: 100vh;
}

.layout-header {
  background-color: #304156;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
}

.system-title {
  color: #fff;
  margin: 0 0 0 20px;
  font-size: 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.username {
  color: #fff;
}

.layout-aside {
  background-color: #304156;
  transition: width 0.3s;
  overflow-x: hidden;
}

.layout-main {
  background-color: #f0f2f5;
  padding: 20px;
}

.el-menu {
  border-right: none;
}
</style>